//
//  BattlegroundScene.swift
//  aircraftBattle1
//
//  Created by 许洋 on 2024/5/16.
//

import SpriteKit
import AVFoundation


class BattlegroundScene:SKScene {
    private var bgNode:SKSpriteNode!
    private var battlegroundNode1:SKSpriteNode!
    private var battlegroundNode2:SKSpriteNode!
    private var battlegroundNode3:SKSpriteNode!
    private var confirmNode:SKSpriteNode!
    private var selectIndex:NSInteger!

    
    override func didMove(to view: SKView) {
        
        bgNode = childNode(withName: "bg") as? SKSpriteNode
        bgNode.size = self.size
        battlegroundNode1 = childNode(withName: "BattlegroundNode1") as? SKSpriteNode
        battlegroundNode2 = childNode(withName: "BattlegroundNode2") as? SKSpriteNode
        battlegroundNode3 = childNode(withName: "BattlegroundNode3") as? SKSpriteNode
        confirmNode = childNode(withName: "Confirm") as? SKSpriteNode
        selectIndex = UserDefaults.standard.integer(forKey: "BATTLEGROUND")
        updateAircraftState()

    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard  let touch = touches.first else {
            return
        }
        let touchLocation = touch.location(in: self)
        if  battlegroundNode1.contains(touchLocation) {
            selectIndex = 0
        }
        if  battlegroundNode2.contains(touchLocation) {
            selectIndex = 1
        }
        if  battlegroundNode3.contains(touchLocation) {
            selectIndex = 2

        }
        updateAircraftState()
        
        if  confirmNode.contains(touchLocation) {
            UserDefaults.standard.set(selectIndex, forKey: "BATTLEGROUND")
            let reveal = SKTransition.doorsCloseHorizontal(withDuration: TimeInterval(0.5))
            let mainScene = HomeScene(fileNamed: "HomeScene")
            mainScene?.size = self.size
            mainScene?.scaleMode = .aspectFill
            self.view?.presentScene(mainScene!, transition: reveal)
            
        }


        
    }
    func updateAircraftState() {
        switch selectIndex{
        case 0:
            battlegroundNode1.texture = SKTexture(imageNamed: "")
            battlegroundNode2.texture = SKTexture(imageNamed: "")
            battlegroundNode3.texture = SKTexture(imageNamed: "")

            break
        case 1:
            battlegroundNode1.texture = SKTexture(imageNamed: "")
            battlegroundNode2.texture = SKTexture(imageNamed: "")
            battlegroundNode3.texture = SKTexture(imageNamed: "")
            break
        case 2:
            battlegroundNode1.texture = SKTexture(imageNamed: "")
            battlegroundNode2.texture = SKTexture(imageNamed: "")
            battlegroundNode3.texture = SKTexture(imageNamed: "")
            break
        default:
            break
        }

    }
}
